<script setup lang="ts">
import eventDetails from '../eventDetails/index.vue';
import surroundingResources from '../surroundingResources/index.vue';
import { useIntelligentAnalyticsStore } from '@/store/modules/IntelligentAnalytics/useIntelligentAnalyticsStore';
import GalleryMapTools from '../GalleryMapTools/index.vue';
import AnalyzeLayers from '../AnalyzeLayers/index.vue';
import { useCesiumEntity } from '@/views/IntelligentAnalytics/config/useCesiumEntity';
import legendData from '@/utils/legend/legendData';
import goBack from '@/components/goBack/index.vue';
import { useCesiumPoints } from '@/hooks/useCesiumPoints';
import componentsTitle from '@/constants/components/componentsTitle';
import { CesiumGridTool, GridPoint } from '@/utils/CesiumGridTool';
import Legend from '../Legend/index.vue';
import AlarmProcessDialog from '../AlarmProcessDialog/index.vue';
const { addPoint } = useCesiumPoints();
const gridTool = ref(null);

// 使用 Cesium 实体管理 hook
const {
  initVariable,
  addGeo,
  addLine,
  flyTo,
  drawPolygon,
  drawPolygon1,
  drawPolygon2,
  drawPolygon3,
  clearPolygon,
  getEntityById,
  zoomIn,
  zoomOut,
  drawHeatPipeline,
  drawRailPipeline,
  drawIntersectionPipeline,
  drawDistanceConnectionLine
} = useCesiumEntity();

const router = useRouter();
// 返回监测预警
const goBackHandle = () => {
  router.push('/index');
};
const { modelData, riskData, dataSource } = useIntelligentAnalyticsStore();
const { isIndividuallyOpen } = storeToRefs(useIntelligentAnalyticsStore());
const showAnalyzeLayers = ref(false);
const surroundingResourcesMap = ref({
  '救援资源': null,
  '疏散资源': null,
  '防护目标': null
});
const searchList = ref([]);
const addOrRemove = (type: string) => {
  const viewer = window.viewer;
  const { overpressure_range_minor_injury, radius, distance_speed_list, overpressure_range_severe_injury, gis_geometrys, blast_risk_prob_list } =
    modelData.value;
  const { info } = riskData.value;
  if (type !== 'heatMap') {
    if (viewer.entities.getById(type)) {
      clearPolygon(type);
    } else {
      //没有查到范围逻辑
      if (type == 'circle') {
        //轻伤范围
        drawPolygon(info, overpressure_range_minor_injury);
      } else if (type == 'circle1') {
        //搜索范围
        drawPolygon1(info, radius);
      } else if (type == 'circle2') {
        //扩散范围
        drawPolygon2(info, distance_speed_list[0]);
      } else if (type == 'circle3') {
        //重伤范围
        drawPolygon3(info, overpressure_range_severe_injury);
      } else if (type == 'line') {
        addLine(gis_geometrys, blast_risk_prob_list);
      }
    }
  } else {
    // 热力图/网格图逻辑
    if (gridTool.value && gridTool.value.hasGridEntities()) {
      // 如果网格图已存在，则清除
      clearGridMap();
    } else {
      // 如果网格图不存在，则创建
      createGridMap();
    }
  }
};
// 辅助函数：查找管线上距离指定点最近的点
const findNearestPointOnLine = (lineString: string, targetPoint: { longitude: number; latitude: number }) => {
  try {
    // 解析LINESTRING坐标
    const coordsString = lineString.replace(/LINESTRING\s*\(\s*/, '').replace(/\s*\)$/, '');
    const coordPairs = coordsString.split(',');

    let minDistance = Number.MAX_VALUE;
    let nearestPoint = null;

    // 遍历所有线段，找到最近的点
    for (let i = 0; i < coordPairs.length - 1; i++) {
      const startCoords = coordPairs[i].trim().split(/\s+/);
      const endCoords = coordPairs[i + 1].trim().split(/\s+/);

      if (startCoords.length >= 2 && endCoords.length >= 2) {
        const segStart = {
          longitude: parseFloat(startCoords[0]),
          latitude: parseFloat(startCoords[1])
        };
        const segEnd = {
          longitude: parseFloat(endCoords[0]),
          latitude: parseFloat(endCoords[1])
        };

        // 计算点到线段的最近点
        const closestPoint = getClosestPointOnSegment(targetPoint, segStart, segEnd);
        const distance = getDistance(targetPoint, closestPoint);

        if (distance < minDistance) {
          minDistance = distance;
          nearestPoint = closestPoint;
        }
      }
    }

    return nearestPoint;
  } catch (error) {
    console.error('查找最近点失败:', error);
    return null;
  }
};

// 计算点到线段的最近点
const getClosestPointOnSegment = (
  point: { longitude: number; latitude: number },
  segStart: { longitude: number; latitude: number },
  segEnd: { longitude: number; latitude: number }
) => {
  const A = point.longitude - segStart.longitude;
  const B = point.latitude - segStart.latitude;
  const C = segEnd.longitude - segStart.longitude;
  const D = segEnd.latitude - segStart.latitude;

  const dot = A * C + B * D;
  const lenSq = C * C + D * D;

  if (lenSq === 0) return segStart; // 线段长度为0

  let param = dot / lenSq;

  // 限制参数在[0,1]范围内
  param = Math.max(0, Math.min(1, param));

  return {
    longitude: segStart.longitude + param * C,
    latitude: segStart.latitude + param * D
  };
};

// 计算两点间距离（简化计算）
const getDistance = (point1: { longitude: number; latitude: number }, point2: { longitude: number; latitude: number }) => {
  const dx = point2.longitude - point1.longitude;
  const dy = point2.latitude - point1.latitude;
  return Math.sqrt(dx * dx + dy * dy);
};

//创建网格图
const createGridMap = () => {
  if (!gridTool.value) {
    gridTool.value = new CesiumGridTool(window.viewer);
  }
  const { heat_map } = modelData.value;
  const points: GridPoint[] = [];
  for (const key in heat_map) {
    heat_map[key].forEach((item: any) => {
      points.push({
        x: Number(item.point_text.split(',')[0]) - 0.006,
        y: Number(item.point_text.split(',')[1]) - 0.0007,
        value: Number(item.point_text.split(',')[2])
      });
    });
  }

  if (points.length > 0) {
    gridTool.value.drawGridByPointsWithRadius(points);
  }
};

// 清除网格图
const clearGridMap = () => {
  if (gridTool.value) {
    try {
      gridTool.value.clearGrid();
    } catch (error) {
      console.log(error);
    }
  }
};
//获取路径规划
const getRoutePlanningHandler = (item: any) => {
  if (item.geo_resource[2].value) {
    addGeo(item.geo_resource[2].value, item.name);
  }
};
const handleSelect = (item: any) => {
  isIndividuallyOpen.value = true;
  getEntityById(item, dataSource, isIndividuallyOpen.value);
};
//点击资源弹全部的框
const showPopUp = (data: any, name: string) => {
  isIndividuallyOpen.value = false;
  data.forEach((item: any) => {
    getEntityById(item, dataSource, isIndividuallyOpen.value);
  });
};
// 保存原始图例状态
const originalLegendState = ref([]);

const init = () => {
  initVariable();
  // 保存原始状态
  originalLegendState.value = legendData.value.modeling.map((item) => ({ ...item }));
  const {
    overpressure_range_minor_injury,
    radius,
    distance_speed_list,
    overpressure_range_severe_injury,
    gis_geometrys,
    blast_risk_prob_list,
    hospitalMap,
    evacuationMap,
    criticalTargetsMap,
    nearest_heat_line,
    nearest_heat_line_distance,
    nearest_rail_line,
    nearest_rail_line_distance,
    nearest_lines_intersection
  } = modelData.value;
  const { info } = riskData.value;
  addPoint(info, info.alarmTypeName, componentsTitle.ALARM_TYPE);
  flyTo(info);
  drawPolygon(riskData.value.info, overpressure_range_minor_injury);
  drawPolygon1(info, radius);
  drawPolygon2(info, distance_speed_list[0]);
  drawPolygon3(info, overpressure_range_severe_injury);
  addLine(gis_geometrys, blast_risk_prob_list);
  createGridMap();

  // 报警点坐标（用于距离连接线）
  const alarmPoint = {
    longitude: parseFloat(info.longitude),
    latitude: parseFloat(info.latitude)
  };

  // 绘制热力管线（绿色）
  if (nearest_heat_line) {
    drawHeatPipeline(nearest_heat_line, 'heat_pipeline', '热力管线');

    // 绘制热力管线距离连接线（紫色）
    const heatDistance = parseFloat(nearest_heat_line_distance);
    if (heatDistance > 0) {
      const nearestPoint = findNearestPointOnLine(nearest_heat_line, alarmPoint);
      if (nearestPoint) {
        drawDistanceConnectionLine(alarmPoint, nearestPoint, heatDistance, 'heat_distance_line');
      }
    }
  }

  // 绘制轨交管线（蓝色）
  if (nearest_rail_line) {
    drawRailPipeline(nearest_rail_line, 'rail_pipeline', '轨道交通');

    // 绘制轨交管线距离连接线（紫色）
    const railDistance = parseFloat(nearest_rail_line_distance);
    if (railDistance > 0) {
      const nearestPoint = findNearestPointOnLine(nearest_rail_line, alarmPoint);
      if (nearestPoint) {
        drawDistanceConnectionLine(alarmPoint, nearestPoint, railDistance, 'rail_distance_line');
      }
    }
  }

  // 绘制溯源管线（红色）
  if (nearest_lines_intersection) {
    drawIntersectionPipeline(nearest_lines_intersection, 'intersection_pipeline', '溯源管线');
  }
  surroundingResourcesMap.value['救援资源'] = hospitalMap;
  surroundingResourcesMap.value['疏散资源'] = evacuationMap;
  surroundingResourcesMap.value['防护目标'] = criticalTargetsMap;

  if (surroundingResourcesMap.value['救援资源']) {
    for (const key in surroundingResourcesMap.value['救援资源']) {
      surroundingResourcesMap.value['救援资源'][key].forEach((item: any) => {
        item.value = item.name;
        searchList.value.push(item);
        getRoutePlanningHandler(item);
        dataSource.push(addPoint(item, item.level_two, '智能分析'));
      });
    }
  }
  if (surroundingResourcesMap.value['防护目标']) {
    for (const key in surroundingResourcesMap.value['防护目标']) {
      surroundingResourcesMap.value['防护目标'][key].forEach((item: any) => {
        item.value = item.name;
        searchList.value.push(item);
        dataSource.push(addPoint(item, item.level_two, '智能分析'));
      });
    }
  }
  if (surroundingResourcesMap.value['疏散资源']) {
    for (const key in surroundingResourcesMap.value['疏散资源']) {
      surroundingResourcesMap.value['疏散资源'][key].forEach((item: any) => {
        item.value = item.name;
        searchList.value.push(item);
        dataSource.push(addPoint(item, item.level_two, '智能分析'));
      });
    }
  }
};

// 重置图例状态的函数
const resetLegendState = () => {
  if (originalLegendState.value.length > 0) {
    originalLegendState.value.forEach((originalItem, index) => {
      if (legendData.value.modeling[index]) {
        legendData.value.modeling[index].checked = originalItem.checked;
      }
    });
  }
};

onMounted(init);

// 在组件销毁时完整清理资源
onUnmounted(() => {
  resetLegendState();
});
const handleLayer = () => {
  showAnalyzeLayers.value = !showAnalyzeLayers.value;
};
const handleBackToTop = () => {
  const { info } = riskData.value;
  flyTo(info);
};
const handleZoomIn = () => {
  zoomIn();
};
const handleZoomOut = () => {
  zoomOut();
};
//燃气报警流程
const showAlarmProcess = ref(false);

const handleAlarm = () => {
  showAlarmProcess.value = true;
};
</script>

<template>
  <go-back @goBack="goBackHandle" />
  <gallery-map-tools @back-to-top="handleBackToTop" @zoom-in="handleZoomIn" @zoom-out="handleZoomOut" @layer="handleLayer" @alarm="handleAlarm" />
  <analyze-layers v-if="showAnalyzeLayers" @close="showAnalyzeLayers = false" :legend="legendData.modeling" @addOrRemove="addOrRemove" />
  <Legend style="position: absolute; top: 65%; right: 27%; z-index: 1000" />

  <!-- 燃气报警流程对话框组件 -->
  <alarm-process-dialog v-model="showAlarmProcess" />
  <div class="mid-container">
    <!-- 左侧容器 -->
    <div class="left-side">
      <div class="basic-panel">
        <div class="basic-panel-title">事件详情</div>
        <div class="basic-panel-content">
          <eventDetails />
        </div>
      </div>
    </div>

    <!-- 右侧容器 -->
    <div class="right-side">
      <div class="basic-panel">
        <div class="basic-panel-title">周边资源</div>
        <div class="basic-panel-content">
          <surroundingResources @showPopUp="showPopUp" @handle-select="handleSelect" :search-list="searchList" :mode-data="surroundingResourcesMap" />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
// 基础变量
$primary-bg: linear-gradient(270deg, rgba(9, 48, 111, 0.4) 0%, rgba(9, 48, 111, 0.8) 100%);
$shadow: 0px 0px 20px #09306f;
$border-radius: 6px;
$title-bg: url(@/assets/largescreen/title-pic.png) no-repeat center center;
$title-font: PangMenZhengDao;
$height: 100%;
$width: 100%;
// 基础面板样式
.basic-panel {
  background: $primary-bg;
  box-shadow: $shadow;
  border-radius: $border-radius;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  height: $height;

  &-title {
    width: $width;
    background: $title-bg;
    background-size: cover;
    padding-left: 5%;
    font-size: 20px;
    color: white;
    line-height: 38px;
    font-family: $title-font;
  }

  &-content {
    font-size: 14px;
    padding-top: 1.5rem;
    height: calc(100% - 1.5rem);
  }
}

// 布局容器
.mid-container {
  display: flex;
  justify-content: space-between;
  width: $width;
  height: $height;
  padding: 50px;
  gap: 20px;
}

// 左侧样式 // 右侧样式
.left-side,
.right-side {
  width: 25%;
  display: flex;
  flex-direction: column;
  gap: 10px;
  z-index: 5;
}
</style>
